package net.xju3_4.controller;

import net.xju3_4.common.framework.simplemvc.RequestMapping;
import net.xju3_4.common.utils.JSONUtil;
import net.xju3_4.common.utils.PageInfo;
import net.xju3_4.common.utils.Result;
import net.xju3_4.entity.User;
import net.xju3_4.service.UserService;
import net.xju3_4.service.impl.UserServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.List;

@RequestMapping("/api/user")
public class UserController {
    UserService userService = new UserServiceImpl();
    //修改提交测试


    //获取当前登录用户
    @RequestMapping("/userInfo.do")
    public void userInfo(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        JSONUtil.printByJSON(response, Result.success(user));
    }

    // 登录
    @RequestMapping("/login.do")
    public void login(HttpServletRequest req, HttpServletResponse resp)  {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = userService.login(username,password); // alt+enter
        if (user != null) {
            HttpSession session = req.getSession();
            session.setAttribute("user", user);
            JSONUtil.printByJSON(resp, Result.success(user, "登录成功"));
        } else {
            JSONUtil.printByJSON(resp,Result.fail("账号或者密码有误"));
        }
    }
    // 添加
    @RequestMapping("/insert.do")
    public void insert(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        req.setCharacterEncoding("utf-8");
        
        // 获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String gender = req.getParameter("gender");
        String roleStr = req.getParameter("role");
        
        // 参数验证
        if (username == null || username.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("用户名不能为空"));
            return;
        }
        if (password == null || password.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("密码不能为空"));
            return;
        }
        if (email == null || email.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("邮箱不能为空"));
            return;
        }
        if (gender == null || gender.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("性别不能为空"));
            return;
        }
        if (roleStr == null || roleStr.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("角色不能为空"));
            return;
        }
        
        // 转换角色为整数
        Integer role;
        try {
            role = Integer.parseInt(roleStr);
            // 验证角色值是否合法
            if (role != 0 && role != 1) {
                JSONUtil.printByJSON(resp, Result.fail("角色值必须为0或1"));
                return;
            }
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(resp, Result.fail("角色值必须为数字"));
            return;
        }

        
        User user = new User();
        user.setRole(role);
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setGender(gender);
        user.setAvatar("default-avatar.jpg"); // 设置默认头像
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        
        try {
            userService.insert(user);
            JSONUtil.printByJSON(resp, Result.success("注册成功"));
        } catch (Exception e) {
            JSONUtil.printByJSON(resp, Result.fail("注册失败：" + e.getMessage()));
        }
    }
    // 根据id查询用户
    @RequestMapping("/selectOne.do")
    public void selectOne(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        req.setCharacterEncoding("utf-8");
        String id = req.getParameter("id");
        User user = userService.selectOne(Integer.parseInt(id));
        JSONUtil.printByJSON(resp, Result.success(user));
    }
    // 删除
    @RequestMapping("/deleted.do")
    public void deleteById(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        req.setCharacterEncoding("utf-8");
        String id = req.getParameter("id");
        userService.deleteById(Integer.parseInt(id));
        JSONUtil.printByJSON(resp, Result.success("删除成功"));
    }
    // 修改
    @RequestMapping("/update.do")
    public void update(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        req.setCharacterEncoding("utf-8");
        User user = new User();
        user.setId(Integer.parseInt(req.getParameter("id")));
        user.setRole(Integer.parseInt(req.getParameter("role")));
        user.setUsername(req.getParameter("username"));
        user.setPassword(req.getParameter("password"));
        user.setEmail(req.getParameter("email"));
        user.setGender(req.getParameter("gender"));
        user.setAvatar(req.getParameter("avatar"));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userService.update(user);
        JSONUtil.printByJSON(resp,Result.success("修改成功"));
    }

    // 条件分页查询
    @RequestMapping("/list.do")
    public void list(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        // 控制层-》业务层-》持久层
        req.setCharacterEncoding("utf-8");
        // 条件查询参数
        String username = req.getParameter("username");
        String gender = req.getParameter("gender");
        // 分页参数  pageNum 第几页   pageSize 每页有多少条
        String pageNoStr = req.getParameter("pageNo");
        String pageSizeStr = req.getParameter("pageSize");
        Integer pageNo = pageNoStr == null ? 1 : Integer.parseInt(pageNoStr);
        Integer pageSize = pageSizeStr == null ? 10 : Integer.parseInt(pageSizeStr);
        PageInfo<User> pageInfo = userService.pageList(username,gender,pageNo,pageSize);
        JSONUtil.printByJSON(resp, Result.success(pageInfo));
    }
    
}
